<?php

// +----------------------------------------------------------------------
// |仓库服务层
// +----------------------------------------------------------------------

namespace app\common\system;

use think\facade\Validate;
use think\facade\Db;
use think\facade\Cache;
use app\common\Model\StroageModel;

class StroagesService
{
    /**
     * 获取仓库列表
     * @param array $param 前台传过来的参数  
     *   
      */

     public static function list($param){
        $model= new StroageModel();
        $where = [];
        $params= $param['params'];
        if($params['status']==2){
            $where[] = ['status', '=', 0];
        }else  if($params['status']==1){
            $where[] = ['status', '=', 1];
        }   
        if($params['is_default']==2){
            $where[] = ['is_default', '=', 0];
        }else  if($params['is_default']==1){
            $where[] = ['is_default', '=', 1];
        }   
        $pk = $model->getPk();      
        $field = $pk . ',name,status,is_default,createtime';          
        $authgroups_list = $model->field($field)->where($where)->order('id asc,status asc')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray();     
        $data['list']=$authgroups_list['data'];
        $data['total']=$authgroups_list['total'];  
        return $data;
     }
    
   /**
     * 仓库修改与及添加  
     * 
     * @return array|Exception
     */
    public static function  create($param){
        $model = new StroageModel();
        $pk = $model->getPk();
        $params= $param['params'];    
        $data=[
            'name' => $params['name'],
            'status' => $params['status'],  
            'is_default' => $params['is_default'],     
        ];

        if($params[$pk]){
             //有值则说明是修改     
             $result =  $model::find($params[$pk])->save($data);
        }else{
            $data['createtime']=datetime();
            $data['createYmd']=(int)date('Ymd',time());
             //执行添加数据
             $result =  $model->save($data);
        }
        if($result){
            return true;
        }else{
            error('修改失败');
        }      
    }

    /**
     * 删除仓库
     * 
     * @return array|Exception
     */
    public static function   delete($param){
        $model = new StroageModel();
        $pk = $model->getPk();
        $params= $param['params'];      
        $result = $model::find( $params[$pk])->delete();
        if($result){
            return true;
        }else{
            error('删除失败');
        }
    }

     /**
     * 库存日志
     * 
     * @return array|Exception
     */
    public static function inventorylog($param){
  
        $model = new StroageModel();
        $params= $param['params'];    
        $where =$map= [];
        //查询添加时间
        if($params['operate_time']){ 
            $operate_date = $params['operate_time'];         
            $operatetime_start  =date('Y-m-d',strtotime($operate_date[0]));
            $operatetime_end = date('Y-m-d',strtotime($operate_date[1]))." 23:59:59";
            $where[]=['a.operate_time','between',[$operatetime_start,$operatetime_end]];
        }
            //操作完结时间
        if($params['create_time']){ 
            $create_date =$params['create_time'];       
            $createtime_start =date('Y-m-d',strtotime($create_date[0]));
            $createtetime_end = date('Y-m-d',strtotime($create_date[1]))." 23:59:59";
            $where[]=['a.create_time','between',[$createtime_start,$createtetime_end]];
        }
    
        if($params['localsku']){         
            $where[]=['b.localsku','like',"%".$params['localsku']."%"];
            $map[]=['localsku','like',"%".$params['localsku']."%"];
        }
        if($params['storage_id']){         
            $where['c.id']=$params['storage_id'];           
        }
       
     
        if( $params['status']==='0'){  
            $where['a.status']=0;     
        }else  if($params['status']){                          
           $where['a.status']=$params['status'];   
        }else{        
            $where[]=['a.status','in',[1]];    
        }
        if($params['log_type']){         
            $where['a.log_type']=$params['log_type'];           
        }
        $field =  'a.id,a.log_type,a.nicakname,a.storage_id,a.notes,a.create_time,a.operate_time,c.name,a.status';        
        $result = Db::name('inventory_log')->alias('a')->join('inventory_detail_log b', 'a.id=b.log_id')->join('storage c', 'c.id=a.storage_id','left')->where($where)->field($field)->group('a.id')->order('a.id desc')->paginate($params['pagesize'])->toArray() ;

        if ($result) {
            $logIdArr = [];
            foreach ($result['data'] as $v) {
                $logIdArr[] = $v['id'];                   
            }            
            $fields =  'localsku,quantity';  
            $datas =Db::name('inventory_detail_log')->where('log_id' ,'in', $logIdArr)->where($map)->select()->toArray();          
         
               foreach ($result['data'] as &$parent) {              
                $parent['children'] = []; // 初始化 children 字段         
                $parent['localsku'] = ''; // 添加一个localsku  
                //获取入库类型 
                $parent['log_type_name'] =  $model->getLogType($parent['log_type']);
                //获取库存日志状态                 
                $parent['status'] =  $model->getStatus($parent['status']);
                foreach ($datas as $child) {
                    if ($parent['id'] == $child['log_id'] ) {                      
                        $parent['children'][] = $child; // 将子体数据添加到父体的 children 字段
                    }
                }
            } 
        }      
        $data['list']=$result['data'];
        $data['total']=$result['total'];  
        return $data;  
    }

    /**
     * 库存日志导出
     * 
     * @return array|Exception
     */
    public static function inventorylog_export($params){
        $model = new StroageModel();           
        $where = [];
        //查询添加时间
        if($params['operate_time']){ 
            $operate_date = $params['operate_time'];         
            $operatetime_start  =date('Y-m-d',strtotime($operate_date[0]));
            $operatetime_end = date('Y-m-d',strtotime($operate_date[1]))." 23:59:59";
            $where[]=['a.operate_time','between',[$operatetime_start,$operatetime_end]];
        }
        //操作完结时间
        if($params['create_time']){ 
            $create_date =$params['create_time'];       
            $createtime_start =date('Y-m-d',strtotime($create_date[0]));
            $createtetime_end = date('Y-m-d',strtotime($create_date[1]))." 23:59:59";
            $where[]=['a.create_time','between',[$createtime_start,$createtetime_end]];
        }    
        if($params['localsku']){         
            $where[]=['b.localsku','like',"%".$params['localsku']."%"];
        }
        if($params['storage_id']){         
            $where['c.id']=$params['storage_id'];           
        }
     
        if( $params['status']==='0'){  
            $where['a.status']=0;     
        }else  if($params['status']){                          
           $where['a.status']=$params['status'];   
        }else{        
            $where[]=['a.status','in',[1]];    
        }
        if($params['log_type']){         
            $where['a.log_type']=$params['log_type'];           
        }
        $field =  'a.log_type,a.nicakname,a.notes,a.create_time,a.operate_time,c.name,a.status,localsku,quantity';        
        $result = Db::name('inventory_log')->alias('a')->join('inventory_detail_log b', 'a.id=b.log_id')->join('storage c', 'c.id=a.storage_id','left')->where($where)->field($field)->order('a.id desc')->select()->toArray() ;
         if($result){
            foreach ($result as &$parent) {  
                //获取入库类型 
                $parent['log_type_name'] =  $model->getLogType($parent['log_type']);
                //获取库存日志状态                 
                $parent['status'] =  $model->getStatus($parent['status']);           
            } 
         }
        return $result;
    }
     
     /**
     * 入库库存界面
     * 
     * @return array|Exception
     */
     public static function storageslist($param){
        $params= $param['params'];    
        $where[] = ['a.inventory_quantity','<>',0];
        //入库时间
        if($params['create_time']){ 
            $create_date =$params['create_time'];       
            $createtime_start =date('Y-m-d',strtotime($create_date[0]));
            $createtetime_end = date('Y-m-d',strtotime($create_date[1]))." 23:59:59";
            $where[]=['create_time','between',[$createtime_start,$createtetime_end]];
        }
    
        if($params['localsku']){         
            $where[]=['localsku','like',"%".$params['localsku']."%"];         
        }
        if($params['storage_id']){         
            $where['a.storage_id']=$params['storage_id'];           
        }       
         
        //计算库值
        $result_total = Db::name('instorage_item')->alias('a')->where($where)->field('sum(inventory_quantity) as total_inventory_quantity,sum(available_quantity) as total_available_quantity,sum(actual_price*inventory_quantity) as total_actual_price')->select();
        $field =  'a.id,a.localsku,a.pwin,a.inventory_quantity,a.create_time,a.available_quantity,a.actual_price,b.name,a.image';        
        $result = Db::name('instorage_item')->alias('a')->join('storage b', 'b.id=a.storage_id','left')->where($where)->field($field)->group('a.id')->order('a.id desc')->paginate($params['pagesize'])->toArray() ;
     
        if($result['data']){
            foreach ($result['data'] as $k=>$v) {  
                $result['data'][$k]['category_name'] ='家居服套装';//分类名称
                $result['data'][$k]['place'] ='3F-2层';//货架
                $result['data'][$k]['stock_age'] =diffDate(strtotime($v['create_time']),time());//库龄
            }
        }
        $data['total_count']= $result_total[0];
        $data['list']=$result['data'];
        $data['total']=$result['total'];  
        return $data; 
     }
      /**
     * 入库库存界面导出数据
     * 
     * @return array|Exception
     */
    public static function  storageslist_export($params){      
        $where[] = ['a.inventory_quantity','<>',0];
        //入库时间
        if($params['create_time']){ 
            $create_date =$params['create_time'];       
            $createtime_start =date('Y-m-d',strtotime($create_date[0]));
            $createtetime_end = date('Y-m-d',strtotime($create_date[1]))." 23:59:59";
            $where[]=['create_time','between',[$createtime_start,$createtetime_end]];
        }
    
        if($params['localsku']){         
            $where[]=['localsku','like',"%".$params['localsku']."%"];         
        }
        if($params['storage_id']){         
            $where['b.id']=$params['storage_id'];           
        }       
     
        
        $field =  'a.id,a.localsku,a.pwin,a.inventory_quantity,a.create_time,a.available_quantity,a.actual_price,b.name,a.image';        
        $result = Db::name('instorage_item')->alias('a')->join('storage b', 'b.id=a.storage_id','left')->where($where)->field($field)->group('a.id')->order('a.id desc')->select()->toArray() ;
     
        if($result){
            foreach ($result as $k=>$v) {  
                $result[$k]['category_name'] ='家居服套装';//分类名称
                $result[$k]['place'] ='3F-2层';//货架
                $result[$k]['stock_age'] =diffDate(strtotime($v['create_time']),time());//库龄
            }
        }        
        return $result; 
     }
}